<template>
  <div>
    <!-- 地图容器 -->
    <div id="map" class="main_map" style="width: 100vw; height: 100vh"></div>
    <div class="btnBox">
      <el-button type="danger" @click="endDrawing">结束此段绘制</el-button>
      <el-button type="success" @click="uploadData">保存</el-button>
      <!-- <el-button type="warning" @click="clearMap">清除</el-button> -->
    </div>
    <div class="display" :style="displaySty" v-show="displayShow">
      <p id="markerId">删除节点</p>
      <p @click="openDialog">插入全景</p>
    </div>
    <p class="deleteLine" v-show="deleteLineShow" :style="deleteLineSty">
      删除此线
    </p>
    <panoramicVue
      :dialogShow="dialogShow"
      :closeDialog="closeDialog"
      :markerInfo="markerInfo"
    ></panoramicVue>
  </div>
</template>

<script>
import { uniq } from "lodash";
import { addNode, getAllNode } from "@/api/map/node";
import panoramicVue from "./panoramicV2.vue";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
let map = null;
let markers = [];
let polylineList = [];
let currentPath = [];
let markerIdCounter = 0;
let currentMarker = {
  info: {},
  marker: null,
};
let displayDom = null;
let deleteLineDom = null;

export default {
  components: { panoramicVue },
  data() {
    return {
      dialogShow: false,
      currentId: 1,
      displayShow: false,
      deleteLineShow: false,
      display: null,
      deleteLine: null,
      displaySty: "",
      deleteLineSty: "",
      markerInfo: {},
    };
  },
  mounted() {
    this.initMap();
    this.getListNode();
    displayDom = document.querySelector(".display");
    deleteLineDom = document.querySelector(".deleteLine");
    markerIdCounter = localStorage.getItem("markerId");
    window.addEventListener("contextmenu", (event) => {
      event.preventDefault(); // 阻止默认右键菜单
    });
  },
  methods: {
    initMap() {
      map = L.map("map", { attributionControl: false }).setView(
        [29.5046, 106.507],
        19
      );
      L.tileLayer("http://dwy.wcsoft.net/tiles/{z}/{x}/{y}.jpg", {
        minZoom: 12,
        maxZoom: 19,
        tms: false,
        attribution: "Created by QGIS",
      }).addTo(map);
      map.on("click", (e) => this.handMapClick(e));
      map.on("mousedown", (e) => {
        this.displayShow = false;
      });
    },
    getMarkIcons(type = 1) {
      return L.icon({
        iconUrl: require(`@/assets/images/dot${type == 0 ? 2 : 1}.png`),
        iconSize: [30, 30],
        iconAnchor: [15, 28],
      });
    },
    handMapClick(e, type, isVr) {
      let latlng = e.latlng;
      // 创建一个标记（Marker），并设置其位置为点击位置的坐标
      let marker = L.marker(latlng, { icon: this.getMarkIcons(isVr) }).addTo(
        map
      );
      let id = type ? e.id : markerIdCounter++;
      marker.on("click", (e) => this.markerClick(e));
      marker.on("contextmenu", (e) => this.markerContextMenu(e, marker, id));
      markers.push({
        id,
        latlng: latlng,
        isVr: isVr !== undefined ? isVr : "1",
      });
      marker.on("mousemove", (e) => {
        marker.bindTooltip(`点${id}`).openTooltip();
      });
      if (type == 1) return;
      if (currentPath.length > 1) {
        currentPath.splice(0, 1);
      }
      currentPath.push({ id, latlng: latlng });
      this.drawPolyline();
    },
    // 结束绘图
    endDrawing() {
      currentPath = [];
    },

    closeDialog(e, param) {
      console.log(e, param);
      // 如果是保存，改变Marker的颜色
      let isVr = "1";
      if (e == 2) {
        isVr = "0";
      }
      this.dialogShow = false;
      if (e == 1) return;
      currentMarker.info.isVr = isVr;
      console.log(currentMarker.marker.setIcon)
      currentMarker.marker.setIcon(this.getMarkIcons(isVr));
    },
    /**
     * @function openDialog
     * @description 打开对话框，用户编辑全景
     * @param {void}
     * @return {void}
     */
    openDialog() {
      if (markerIdCounter > localStorage.getItem("markerId")) {
        this.$modal.msgError(`请先上传所有节点!`);
        return;
      }
      const list = [];
      polylineList.forEach((polyItem) => {
        if (polyItem.ids.includes(currentMarker.info.id)) {
          polyItem.ids.forEach((id) => {
            if (id != currentMarker.info.id) {
              list.push(id);
            }
          });
        }
      });

      this.markerInfo = {
        id: currentMarker.info.id,
        isEdit: currentMarker.info.isVr == "0" ? true : false,
        list: uniq(list),
      };
      if (this.markerInfo.list.length == 0) {
        this.$modal.msgError(`该节点没有相邻节点!`);
        return;
      }
      this.dialogShow = true;
      this.displayShow = false;
    },
    // 结束绘图
    endDrawing() {
      currentPath = [];
    },
    markerClick(e) {
      let markerId = markers.find(
        (item) =>
          item.latlng.lat == e.latlng.lat && item.latlng.lng == e.latlng.lng
      );
      if (currentPath.length > 1) {
        currentPath.splice(0, 1);
      }
      currentPath.push(markerId);
      this.drawPolyline();
    },
    markerContextMenu(e, marker, id) {
      currentMarker.info = markers.find((item) => item.id == id); //获取当前右键的图标
      currentMarker.marker = marker; //获取当前右键的图标
      this.displayShow = true;
      this.displaySty = `left:${e.containerPoint.x}px;top:${e.containerPoint.y}px`;
      const markerIdDom = document.getElementById("markerId");
      markerIdDom.onclick = () => {
        marker.remove();
        this.displayShow = false;
        this.deleteMarker(id);
        markers.splice(
          markers.findIndex((item) => item.id == id),
          1
        );
      };
    },
    deleteMarker(id) {
      this.displayShow = false;
      currentPath = [];
      for (let i = 0; i < polylineList.length; i++) {
        if (polylineList[i].ids.includes(id)) {
          polylineList[i].polyline.remove();
          polylineList.splice(i, 1);
          i--;
        }
      }
    },

    drawPolyline() {
      if (currentPath.length < 2) return;
      let ids = [currentPath[0].id, currentPath[1].id];
      let idsJoin = ids.join();
      if (
        polylineList.find(
          (item) =>
            item.ids.join() == idsJoin || item.ids.reverse().join() == idsJoin
        )
      )
        return;
      let path = currentPath.map((p) => p.latlng);
      let polyline = L.polyline(path, {
        color: "#94D3F7",
        weight: 6,
      }).addTo(map);

      // 将绘制的线路添加到数组中记录
      polylineList.push({
        ids,
        polyline,
      });
      polyline.on("contextmenu", (e) => {
        this.deleteLineSty = `left:${e.containerPoint.x}px;top:${e.containerPoint.y}px`;
        this.deleteLineShow = true;
        deleteLineDom.onclick = () => {
          polyline.remove();
          this.deleteLineShow = false;
          let index = polylineList.findIndex(
            (item) => item.ids.join() == idsJoin
          );
          polylineList.splice(index, 1);
        };
      });
    },
    uploadData() {
      this.$modal.loading("保存中...");
      let datalist = [];
      markers.forEach((item, index) => {
        datalist.push({
          id: item.id,
          ids: {},
          idList: [],
          longitude: item.latlng.lng,
          latitude: item.latlng.lat,
        });
        polylineList.forEach((polyItem) => {
          if (polyItem.ids.includes(item.id)) {
            datalist[index].idList.push(...polyItem.ids);
          }
        });
        datalist[index].idList = [...new Set(datalist[index].idList)].filter(
          (e) => e !== item.id
        );
        datalist[index].ids = Object.fromEntries(
          datalist[index].idList.map((id) => [id, 1])
        );
      });
      localStorage.setItem("markerId", markerIdCounter);
      addNode(datalist).then((res) => {
        this.$modal.closeLoading();
      });
    },
    getListNode() {
      this.$modal.loading("正在绘制节点路线，请稍候...");
      getAllNode().then((res) => {
        res.data?.forEach((item) => {
          let obj = {
            id: item.id,
            latlng: { lat: item.latitude, lng: item.longitude },
          };
          this.handMapClick(obj, 1, item.isVrNode);
          if (!item.ids.length) return;
          item.ids.forEach((id) => {
            let nextNode = res.data.find((e) => e.id == id.id);
            currentPath = [
              {
                id: item.id,
                latlng: { lat: item.latitude, lng: item.longitude },
              },
              {
                id: id.id,
                latlng: { lat: nextNode.latitude, lng: nextNode.longitude },
              },
            ];
            this.drawPolyline();
          });
        });
        console.log(markers);
        this.$modal.closeLoading();
      });
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
.display {
  position: absolute;
  z-index: 8888;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.4);
  background-color: #fff;
  border-radius: 5px;
  padding: 4px 0;
  font-size: 14px;
  line-height: 30px;
  text-align: center;
  width: 100px;
}
.display > p:hover {
  cursor: pointer;
  color: #ff1000;
  font-weight: bold;
}
.deleteLine {
  position: absolute;
  z-index: 8888;
  line-height: 26px;
  text-align: center;
  width: 80px;
  border-radius: 5px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.4);
  background-color: #fff;
  padding: 4px 0;
  font-size: 12px;
}
.deleteLine:hover {
  cursor: pointer;
  color: #ff1000;
  font-weight: bold;
}
.btnBox {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1111;
}

/* 对整个对话框进行样式设置 */
dialog {
  width: 80%;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  padding: 20px;
  background-color: white;
}

/* 对话框标题样式 */
dialog h2 {
  margin-top: 0;
}

/* 关闭按钮样式 */
#closeDialogBtn {
  margin-top: 10px;
  background-color: #f44336;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 3px;
  cursor: pointer;
}

#openDialogBtn {
  padding: 10px 20px;
  background-color: #008cba;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  margin-bottom: 10px;
}
</style>
